package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.help.condition.ConditionHelper;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.OptionalRangeEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.OptionalRangeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.FieldAttrEntityExt;
import com.xbongbong.paas.field.FormulaPoJo;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.KeyValuePojo;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataRepeatVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.businessdata.pojo.dto.ProductListDataDTO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigGetPriceConfigDTO;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigGetPriceConfigVO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.PublicPoolErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.priceset.pojo.PriceSetFormTreePojo;
import com.xbongbong.pro.priceset.pojo.dto.PriceProductSetDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceProductSetDelDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceProductSetSaveDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceSetConditionDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceSetGetDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceSetListDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceSetSaveDTO;
import com.xbongbong.pro.priceset.pojo.dto.PriceSetSortDTO;
import com.xbongbong.pro.priceset.pojo.vo.PriceProductSetListVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceProductSetSaveVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceProductSetVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceSetFormTemplateVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceSetGetConditionVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceSetGetVO;
import com.xbongbong.pro.priceset.pojo.vo.PriceSetSaveVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.BusinessFieldEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CustomerExpressEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.product.OpportunityProductEnum;
import com.xbongbong.saas.enums.product.PriceProductEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.enums.product.PriceSetScopeEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.service.PriceSetService;
import com.xbongbong.saas.service.ProductCategoryService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.toolbox.handle.WebCommonDataValueMatchHandle;
import com.xbongbong.saas.service.toolbox.handle.WebListDataValueMatchHandle;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.ConditionEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.PriceProductSetEntity;
import com.xbongbong.sys.domain.entity.PriceSetEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.PriceProductSetModel;
import com.xbongbong.sys.model.PriceSetModel;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

@Service("priceSetService")
public class PriceSetServiceImpl implements PriceSetService {

    private static final Logger LOG = LoggerFactory.getLogger(PriceSetServiceImpl.class);

    @Resource
    private PriceSetModel priceSetModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private PriceProductSetModel priceProductSetModel;
    @Resource
    private ProductService productService;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private ProductCategoryService productCategoryService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private WebCommonDataValueMatchHandle webCommonDataValueMatchHandle;
    @Resource
    private WebListDataValueMatchHandle webListDataValueMatchHandle;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private ConditionHelper conditionHelper;

    @Override
    public CompanyConfigGetPriceConfigVO getPriceSet(PriceSetListDTO priceSetListDTO) throws XbbException {
        CompanyConfigGetPriceConfigVO companyConfigGetPriceConfigVO = new CompanyConfigGetPriceConfigVO();
        String corpid = priceSetListDTO.getCorpid();

        Map<String, Object> priceParam = new HashMap<>();
        priceParam.put(ParameterConstant.CORPID, corpid);
        priceParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        priceParam.put(ParameterConstant.ORDER_BY_STR, "priority");
        priceParam.put(ParameterConstant.PAGE, priceSetListDTO.getPage());
        PageHelper pageHelper = PageHelperUtil.getPageHelper(priceParam, priceSetModel, priceSetListDTO.getPageSize());
        List<PriceSetEntity> entitys = (List<PriceSetEntity>) PageHelperUtil.getEntityList(priceParam, pageHelper, priceSetModel);

        PaasFormEntityExt formEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        companyConfigGetPriceConfigVO.setPriceSetList(entitys);
        companyConfigGetPriceConfigVO.setPageHelper(pageHelper);
        companyConfigGetPriceConfigVO.setAppId(formEntityExt.getAppId());
        companyConfigGetPriceConfigVO.setFormId(formEntityExt.getId());
        return companyConfigGetPriceConfigVO;
    }

    @Override
    public PriceSetGetVO priceEnableOrClose(CompanyConfigGetPriceConfigDTO companyConfigGetPriceConfigDTO) throws XbbException {
        PriceSetGetVO priceSetGetVO = new PriceSetGetVO();
        Long dataId = companyConfigGetPriceConfigDTO.getDataId();
        String corpid = companyConfigGetPriceConfigDTO.getCorpid();
        Integer enable = companyConfigGetPriceConfigDTO.getEnable();
        if (Objects.isNull(enable)) {
            return priceSetGetVO;
        }

        PriceSetEntity priceSetEntity = priceSetModel.getByKey(dataId, corpid);
        if (priceSetEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }

        priceSetEntity.setEnable(companyConfigGetPriceConfigDTO.getEnable());
        priceSetModel.update(priceSetEntity);

        priceSetGetVO.setData(priceSetEntity);
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
        return priceSetGetVO;
    }

    @Override
    public PriceSetGetVO delPriceSet(CompanyConfigGetPriceConfigDTO companyConfigGetPriceConfigDTO) throws XbbException {
        PriceSetGetVO priceSetGetVO = new PriceSetGetVO();
        Long dataId = companyConfigGetPriceConfigDTO.getDataId();
        String corpid = companyConfigGetPriceConfigDTO.getCorpid();

        PriceSetEntity priceSetEntity = priceSetModel.getByKey(dataId, corpid);
        priceProductSetModel.deleteByPriceId(dataId, corpid);
        priceSetModel.deleteByKey(dataId, corpid);
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);

        priceSetModel.updateBatchPriority(corpid, priceSetEntity.getPriority());
        return priceSetGetVO;
    }

    @Override
    public PriceSetGetConditionVO getCondition(PriceSetConditionDTO priceSetConditionDTO) throws XbbException {
        PriceSetGetConditionVO priceSetGetConditionVO = new PriceSetGetConditionVO();

        String corpid = priceSetConditionDTO.getCorpid();
        Long formId = priceSetConditionDTO.getFormId();


        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        if (explainEntity == null) {
            throw new XbbException(PublicPoolErrorCodeEnum.API_ERROR_218011);
        }

        String explains = explainEntity.getExplains();
        List<FieldAttrEntity> explainList = JsonHelperUtil.parseArray(explains, FieldAttrEntity.class);
        List<JSONObject> selectInfo = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer enable = fieldAttrEntity.getIsOpen();
            if (enable == null || BasicConstant.NO_USE.equals(enable)) {
                continue;
            }
            if (!ShowTypeEnum.listShow(fieldAttrEntity.getShowType())) {
                continue;
            }
            String alias = fieldAttrEntity.getAttr();
            Integer isRedundant = fieldAttrEntity.getIsRedundant();
            Integer fieldType = fieldAttrEntity.getFieldType();
            DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
            Object initValue = (defaultAttr != null && defaultAttr.getDefaultValue() != null) ? defaultAttr.getDefaultValue() : "";
            List<KeyValuePojo> valueArr = new ArrayList<>();

            if (isRedundant == 0 && FieldTypeEnum.COMBO.getType().equals(fieldType)) {
                valueArr = getValueArr(corpid, formId, alias);
            }
            if (valueArr.isEmpty() && fieldAttrEntity.getItems() != null) {
                valueArr = format2KeyValuePojo(fieldAttrEntity.getItems());
            }
            getByType(selectInfo, fieldAttrEntity.getAttrName(), alias, fieldType, valueArr, initValue.toString(), isRedundant);
        }
        priceSetGetConditionVO.setList(selectInfo);

        return priceSetGetConditionVO;
    }

    @Override
    public PriceProductSetListVO getPriceProductSet(PriceProductSetDTO priceProductSetDTO) throws XbbException {
        PriceProductSetListVO priceProductSetVO = new PriceProductSetListVO();
        String corpid = priceProductSetDTO.getCorpid();
        Long dataId = priceProductSetDTO.getDataId();
        List<ConditionsEntityExt> conditions = priceProductSetDTO.getConditions();
        ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
        if (CollectionsUtil.isNotEmpty(conditions)) {
            conditionsEntityExt = conditions.get(0);
        }

        List<FieldAttrEntity> headList = getHeadList(corpid);
        List<FieldAttrEntity> items = (List<FieldAttrEntity>) headList.get(0).getSubForm().getItems();
        FieldAttrEntityExt linkProductField = new FieldAttrEntityExt();
        linkProductField.setAttr(ListOptionEnum.OPTION.getAttr());
        linkProductField.setAttrName(ListOptionEnum.OPTION.getAttrName());
        linkProductField.setFieldType(FieldTypeEnum.OPTION.getType());
        linkProductField.setDisableListSort(1);
        linkProductField.setAttrNameEn(linkProductField.getAttrNameEn());
        items.add(0, linkProductField);

        Map<String, Object> param = new HashMap<>();
        param.put("priceId", dataId);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.PRODUCT_ID_IN, conditionsEntityExt.getValue());
        param.put(ParameterConstant.PAGE, priceProductSetDTO.getPage());
        PageHelper pageHelper = PageHelperUtil.getPageHelper(param, priceProductSetModel, priceProductSetDTO.getPageSize());
        List<PriceProductSetEntity> entitys = (List<PriceProductSetEntity>) PageHelperUtil.getEntityList(param, pageHelper, priceProductSetModel);

        List<PaasFormDataEntityExt> formDataList = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(entitys)) {
            // 产品信息
            Set<Long> productIdSet = new HashSet<>();
            entitys.forEach(priceProductSetEntity -> productIdSet.add(priceProductSetEntity.getProductId()));
            List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
            productService.setChildSpecification(productEntityList, corpid);
            PaasFormExplainEntity formExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            if (formExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            List<FieldAttrEntity> explainList = JSONArray.parseArray(formExplainEntity.getExplains(), FieldAttrEntity.class);
            List<String> fieldList = BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
            explainList = handleExplain(explainList, fieldList);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
            explainList.forEach((item) -> {
                explainMap.put(item.getAttr(), item);
                if (Objects.equals(ProductEnum.UNIT.getAttr(), item.getAttr())) {
                    if (CollectionsUtil.isNotEmpty(productItems)) {
                        item.setItems(productItems);
                    }
                }
            });
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setPaasFormDataESList(productEntityList);
            formDataListVO.setHeadList(explainList);
            formDataListVO.setForm(paasFormEntityExt);
            formDataListVO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());

            Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
            productEntityList.forEach(item -> productMap.put(item.getDataId(), item));
            Map<Long, List<MultiUnitPricePoJo>> priceMapByProductIdSet = productUnitPriceModel.getPriceMapByProductIdSet(corpid, productIdSet);
            Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
            List<ItemPoJo> businessUnitItems = relativeProductHelp.getBusinessUnitItems(corpid);

            // 产品首列添加删除按钮
            JSONObject option = new JSONObject();
            ButtonPojo buttonPojo = new ButtonPojo();
            buttonPojo.setAttr(SaasButtonEnum.DEL.getAttr());
            buttonPojo.setValue(SaasButtonEnum.DEL.getValue());
            buttonPojo.setDisabled(0);
            option.put("value", Collections.singleton(buttonPojo));
            for (PriceProductSetEntity entity : entitys) {
                Long productId = entity.getProductId();
                JSONObject priceProductData = new JSONObject();
                PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
                PaasFormDataEntityExt productEntity = productMap.get(productId);
                if (productEntity != null) {
                    JSONObject productData = productEntity.getData();
                    priceProductData.put(PriceProductEnum.NAME.getAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                    priceProductData.put(PriceProductEnum.PRODUCT_NO.getAttr(), productData.getString(ProductEnum.PRODUCT_NO.getAttr()));
                    priceProductData.put(PriceProductEnum.SPECIFICATION.getAttr(), productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                    priceProductData.put(PriceProductEnum.PRODUCT_IMGS.getAttr(), productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()));
                    JSONObject unitObj = new JSONObject();
                    if (Objects.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE)) {
                        List<MultiUnitPricePoJo> multiUnitPricePoJos = priceMapByProductIdSet.get(productEntity.getId());
                        priceProductData.put(ProductConstant.PRICE, multiUnitPricePoJos);
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(productData.getLongValue(ProductEnum.UNIT.getAttr()));
                        priceProductData.put(ProductConstant.TRANSFORM_UNIT_RATE, multiUnitItemPoJo);
                        productData.put(ProductConstant.TRANSFORM_UNIT_RATE, multiUnitItemPoJo);
                        for (UnitItemPoJo itemPoJo : multiUnitItemPoJo.getItemDataPoJoList()) {
                            if (Objects.equals(itemPoJo.getValue().toString(), entity.getProductUnit())) {
                                priceProductData.put(PriceProductEnum.UNIT.getAttr(), itemPoJo.getText());
                                unitObj.put(StringConstant.TEXT, itemPoJo.getText());
                                unitObj.put(StringConstant.VALUE, itemPoJo.getValue());
                                break;
                            }
                        }
                    } else {
                        for (ItemPoJo item : productItems) {
                            if (Objects.equals(item.getValue(), entity.getProductUnit())) {
                                priceProductData.put(PriceProductEnum.UNIT.getAttr(), item.getText());
                                unitObj.put(StringConstant.TEXT, item.getText());
                                unitObj.put(StringConstant.VALUE, item.getValue());
                                break;
                            }
                        }
                    }
                    priceProductData.put(BasicConstant.ID, productEntity.getDataId());
                    priceProductData.put(BasicConstant.DATAID, productEntity.getDataId());
                    productData.put(ProductEnum.SERIALNO.getAttr(), productData.getString(ProductEnum.PRODUCT_NO.getAttr()));
                    JSONObject productObj = new JSONObject();
                    productObj.put("data", productData);
                    productObj.put("sourceData", productData);
                    productObj.put("dataId", productEntity.getDataId());
                    productObj.put("id", productEntity.getDataId());
                    JSONObject dataObj = new JSONObject();
                    dataObj.put(ProductEnum.NAME.getAttr(), productObj);
                    dataObj.put(ProductEnum.UNIT.getAttr(), unitObj);
                    priceProductData.put("productData", dataObj);
                }
                priceProductData.put(PriceProductEnum.DISCOUNT.getAttr(), entity.getDiscount());
                priceProductData.put(PriceProductEnum.PRICE.getAttr(), entity.getProductPrice());
                priceProductData.put(PriceProductEnum.SELLING_PRICE.getAttr(), entity.getSellingPrice());
                priceProductData.put(PriceProductEnum.SELLING_PRICE_UP.getAttr(), entity.getPriceCap());
                priceProductData.put(PriceProductEnum.SELLING_PRICE_DOWN.getAttr(), entity.getPriceFloor());
                priceProductData.put(StringConstant.BUSINESS_PRODUCT_ID, entity.getId());

                priceProductData.put(ListOptionEnum.OPTION.getAttr(), option);
                paasFormDataEntityExt.setData(priceProductData);
                formDataList.add(paasFormDataEntityExt);
            }
            productService.setChildSpecification(productEntityList, corpid);
        }
        priceProductSetVO.setFormDataList(formDataList);
        priceProductSetVO.setHeadList(items);
        priceProductSetVO.setBusinessType(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode());
        priceProductSetVO.setPageHelper(pageHelper);
        return priceProductSetVO;
    }

    private List<FieldAttrEntity> getHeadList(String corpid) throws XbbException {
        List<FieldAttrEntity> subItems = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 马老板说要支持自定义字段展示，后果他负责
        PaasFormExplainEntity form = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(form.getExplains(), FieldAttrEntity.class);
        List<Integer> fieldType = Arrays.asList(FieldTypeEnum.DEPT.getType(), FieldTypeEnum.DEPT_GROUP.getType(), FieldTypeEnum.USER.getType(), FieldTypeEnum.USER_GROUP.getType(), FieldTypeEnum.LINK_DATA.getType(), FieldTypeEnum.SEPARATOR.getType(), FieldTypeEnum.ADDRESS.getType(), FieldTypeEnum.LOCATION.getType(), FieldTypeEnum.IMAGE.getType(), FieldTypeEnum.UPLOAD.getType(), FieldTypeEnum.SUB_FORM.getType(), FieldTypeEnum.MEMO.getType());
        explainList = explainList.stream().filter(fieldAttrEntity -> (BasicConstant.ONE.equals(fieldAttrEntity.getIsRedundant()) && !fieldType.contains(fieldAttrEntity.getFieldType()))).collect(Collectors.toList());
        List<LinkedAttrPoJo> linkedAttr = new ArrayList<>();
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            LinkedAttrPoJo linkedAttrPoJo = new LinkedAttrPoJo();
            linkedAttrPoJo.setAttr(fieldAttrEntity.getAttr());
            linkedAttrPoJo.setAttrName(fieldAttrEntity.getAttrName());
            linkedAttrPoJo.setEditable(fieldAttrEntity.getEditable());
            linkedAttrPoJo.setFieldType(fieldAttrEntity.getFieldType());
            linkedAttrPoJo.setSaasAttr(fieldAttrEntity.getSaasAttr());
            linkedAttrPoJo.setVisible(fieldAttrEntity.getVisible());

            linkedAttr.add(linkedAttrPoJo);
        }

        PaasFormExplainEntity contractFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), "0");
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(contractFormExplain.getExplains());
        FieldAttrEntity contractProductField = explainMap.get(SalesOpportunityEnum.PRODUCTS.getAttr());
        List<? extends FieldAttrEntity> items = contractProductField.getSubForm().getItems();
        LinkInfoPojo linkInfoPojo = null;
        for (FieldAttrEntity item : items) {
            if (OpportunityProductEnum.PRODUCT.getAttr().equals(item.getAttr())) {
                linkInfoPojo = item.getLinkInfo();
                break;
            }
        }

        for (PriceProductEnum priceProductEnum : PriceProductEnum.values()) {
            FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
            fieldAttrEntity.setAttr(priceProductEnum.getAttr());
            fieldAttrEntity.setAttrName(priceProductEnum.getAttrName());
            fieldAttrEntity.setSaasAttr(priceProductEnum.getSaasAttr());
            fieldAttrEntity.setFieldType(priceProductEnum.getFieldType());
            fieldAttrEntity.setSort(priceProductEnum.getSort());
            fieldAttrEntity.setVisible(priceProductEnum.getVisible());
            fieldAttrEntity.setRequired(priceProductEnum.getRequired());
            fieldAttrEntity.setEditable(priceProductEnum.getEditable());
            fieldAttrEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
            fieldAttrEntity.setParentAttr("array_1");
            if (FieldTypeEnum.LINK_DATA.getType().equals(fieldAttrEntity.getFieldType())) {
                LinkInfoPojo linkInfo = new LinkInfoPojo();
                linkInfo.setLinkAppId(form.getAppId());
                linkInfo.setLinkBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                linkInfo.setLinkFormId(form.getFormId());
                linkInfo.setLinkKey(ProductEnum.NAME.getAttr());
                linkInfo.setLinkMenuId(form.getMenuId());
                linkInfo.setLinkSaasMark(form.getSaasMark());

                linkInfo.setLinkKeyAttr(linkInfoPojo.getLinkKeyAttr());
                linkInfoPojo.getLinkedAttr().addAll(linkedAttr);
                linkInfo.setLinkedAttr(linkInfoPojo.getLinkedAttr());
                List<LinkedAttrPoJo> linkedShowAttr = linkInfoPojo.getLinkedShowAttr();
                linkedShowAttr.removeIf(linkedAttrPoJo -> Objects.equals(linkedAttrPoJo.getAttr(), ProductEnum.BARCODE.getAttr()));
                linkInfo.setLinkedShowAttr(linkedShowAttr);
                fieldAttrEntity.setLinkInfo(linkInfo);
                fieldAttrEntity.setSaasAttr("product");
            } else if (PriceProductEnum.DISCOUNT.equals(priceProductEnum)) {
                DefaultAttrPoJo defaultAttrPoJo = new DefaultAttrPoJo();
                FormulaPoJo formulaInfo = new FormulaPoJo();
                String formula = "IF(OR(ISEMPTY({self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr() + "}),ISEMPTY({self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.SELLING_PRICE.getAttr() + "})," + "{self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.SELLING_PRICE.getAttr() + "}==0" + ",{self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr() + "}==0),100" +
                        ",MULTIPLY(DIVIDE({self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.SELLING_PRICE.getAttr() + "},{self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr() + "}),100,2))";
                JSONObject labelMap = new JSONObject();
                labelMap.put("self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr(), "关联产品.单价");
                labelMap.put("self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.SELLING_PRICE.getAttr(), "关联产品.售价（元）");
                formulaInfo.setFormula(formula);
                formulaInfo.setLabelMap(labelMap);
                defaultAttrPoJo.setDefaultType("formula");
                defaultAttrPoJo.setFormulaInfo(formulaInfo);
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            } else if (PriceProductEnum.SELLING_PRICE.equals(priceProductEnum)) {
                DefaultAttrPoJo defaultAttrPoJo = new DefaultAttrPoJo();
                FormulaPoJo formulaInfo = new FormulaPoJo();
                String formula = "DIVIDE(MULTIPLY({self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr() + "},{self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.DISCOUNT.getAttr() + "}),100,6)";
                JSONObject labelMap = new JSONObject();
                labelMap.put("self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.PRICE.getAttr(), "关联产品.单价");
                labelMap.put("self." + PriceSetEnum.PRODUCT.getAttr() + "." + SelectProductEnum.DISCOUNT.getAttr(), "关联产品.折扣（%）");
                formulaInfo.setFormula(formula);
                formulaInfo.setLabelMap(labelMap);
                defaultAttrPoJo.setDefaultType("formula");
                defaultAttrPoJo.setFormulaInfo(formulaInfo);
                fieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
            }
            subItems.add(fieldAttrEntity);
        }
        FieldAttrEntity productField = new FieldAttrEntity();
        productField.setFieldType(FieldTypeEnum.SELECT_PRODUCT.getType());
        productField.setAttr("array_1");
        productField.setSaasAttr("products");
        productField.setAttrName("添加产品明细");
        productField.setVisible(1);
        productField.setEditable(1);
        productField.setSaasMark(SaasMarkEnum.SAAS.getCode());
        SubFormPoJo subFormPoJo = new SubFormPoJo();
        subFormPoJo.setItems(subItems);
        productField.setSubForm(subFormPoJo);

        return Collections.singletonList(productField);
    }

    @Override
    public PriceSetFormTemplateVO getTemplateForm(BaseDTO baseDTO) throws XbbException {
        PriceSetFormTemplateVO priceSetFormTemplateVO = new PriceSetFormTemplateVO();
        String corpid = baseDTO.getCorpid();
        // 获取已启用的客户模板
        List<PaasFormEntityExt> templateList = paasFormModel.getEnableFormList(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        // 客户应用id
        Long appId = null;
        List<PriceSetFormTreePojo> templateTree = new ArrayList<>();
        for (PaasFormEntityExt entityExt : templateList) {
            //过滤掉没有使用权限的SASS多模板表单
            List<OptionalRangeEntity> optionalRangeList = JSONObject.parseArray(entityExt.getPermission(), OptionalRangeEntity.class);
            Boolean noPermission = optionalRangeList != null && !optionalRangeList.isEmpty() && paasFormHelp.haveNoPermission(baseDTO.getLoginUser(), optionalRangeList);
            if (Objects.equals(entityExt.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && RedundantTemplateTypeEnum.isMultiTemplate(entityExt.getBusinessType()) && noPermission) {
                continue;
            }
            //
            if (Objects.isNull(appId)) {
                appId = entityExt.getAppId();
            }
            long id = entityExt.getId();
            PriceSetFormTreePojo pojo = new PriceSetFormTreePojo();
            pojo.setFormId(id);
            pojo.setName(entityExt.getName());
            templateTree.add(pojo);
        }

        priceSetFormTemplateVO.setFormTree(templateTree);
        priceSetFormTemplateVO.setAppId(appId);
        priceSetFormTemplateVO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        priceSetFormTemplateVO.setBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
        return priceSetFormTemplateVO;
    }

    @Override
    public PriceSetSaveVO savePriceSet(PriceSetSaveDTO priceSetSaveDTO) throws XbbException {
        PriceSetSaveVO priceSetSaveVO = new PriceSetSaveVO();
        String corpid = priceSetSaveDTO.getCorpid();
        PriceSetEntity priceSetEntity = priceSetSaveDTO.getPriceSet();
        if (priceSetEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "价目表数据不能为空");
        }
        String priceName = priceSetEntity.getName();
        if (StringUtil.isEmpty(priceName)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "价目表数据不能为空");
        } else if (priceName.length() > 100) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "价目表名称字数不能多于100个");
        }

        Long id = priceSetEntity.getId() == null ? 0L : priceSetEntity.getId();
        boolean isNew = id <= 0;

        Long startTime = priceSetEntity.getStartTime();
        Long endTime = priceSetEntity.getEndTime();
        if (startTime != null && endTime == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.TIME_REQUIRED);
        } else if (startTime == null && endTime != null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.TIME_REQUIRED);
        } else if (startTime != null && endTime != null && startTime > endTime) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_TIME_LESS_END_TIME);
        }
        // 校验价目表名称是否重复
        Map<String, Object> priceParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        priceParam.put(ParameterConstant.CORPID, corpid);
        priceParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        priceParam.put(ParameterConstant.COLUMNS, "name");
        if (!isNew) {
            priceParam.put("idNotEqual", priceSetSaveDTO.getDataId());
        }
        List<PriceSetEntity> entitys = priceSetModel.findEntitys(priceParam);
        boolean match = entitys.stream().anyMatch(item -> Objects.equals(priceName, item.getName()));
        if (match) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(ErrorMessageConstant.NO_REPEAT_PRICE));
        }
        if (isNew) {
            CompanyConfigEntity companyConfigEntity = companyConfigModel.getByConfigAlias(CompanyConfigEnum.PRICE_SET_COUNT.getAlias(), corpid);
            Integer priceSetNum = Objects.nonNull(companyConfigEntity) && Objects.nonNull(companyConfigEntity.getConfigValue()) ? Integer.valueOf(companyConfigEntity.getConfigValue()) : 100;
            if (entitys.size() > priceSetNum) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.NO_MORE_THAN_PRICE), priceSetNum));
            }
            long now = DateTimeUtil.getInt();
            priceSetEntity.setAddTime(now);
            priceSetEntity.setUpdateTime(now);
            priceSetEntity.setCorpid(corpid);
            priceSetEntity.setCreator(priceSetSaveDTO.getLoginUserName());
            if (Objects.equals(priceSetSaveDTO.getIsImport(), 1)) {
                priceSetEntity.setEnable(BasicConstant.ZERO);
            } else {
                priceSetEntity.setEnable(BasicConstant.ONE);
            }
            priceSetEntity.setDel(DelEnum.NORMAL.getDel());
            // 优先级
            Integer priority = priceSetModel.getMaxPriority(corpid);
            if (priority == null || priority == 0) {
                priority = 1;
            } else {
                priority++;
            }
            priceSetEntity.setPriority(priority);
            priceSetModel.insert(priceSetEntity);
        } else {
            priceSetModel.update(priceSetEntity);
        }

        priceSetSaveVO.setDataId(priceSetEntity.getId());
        priceSetSaveVO.setBusinessType(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode());
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
        return priceSetSaveVO;
    }

    @Override
    public PriceProductSetSaveVO savePriceProductSet(PriceProductSetSaveDTO priceProductSetSaveDTO) throws XbbException {
        PriceProductSetSaveVO priceProductSetSaveVO = new PriceProductSetSaveVO();
        String corpid = priceProductSetSaveDTO.getCorpid();
        Long dataId = priceProductSetSaveDTO.getDataId();
        JSONArray dataList = priceProductSetSaveDTO.getSupplierProducts();

        Map<String, Object> productParam = new HashMap<>();
        productParam.put(ParameterConstant.CORPID, corpid);
        productParam.put("priceId", dataId);
        productParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        Integer count = priceProductSetModel.getEntitysCount(productParam);
        if ((count + dataList.size()) > 5000) {
            throw new XbbException();
        }
        List<Long> businessProductIdList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject priceProductData = dataList.getJSONObject(i);
            Long businessProductId = priceProductData.getLongValue(StringConstant.BUSINESS_PRODUCT_ID);
            if (businessProductId > 0L) {
                businessProductIdList.add(businessProductId);
            }
        }
        Map<Long, PriceProductSetEntity> orginProductMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(businessProductIdList)) {
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.ID_IN, businessProductIdList);
            List<PriceProductSetEntity> entitys = priceProductSetModel.findEntitys(param);
            entitys.forEach(priceProductSetEntity -> orginProductMap.put(priceProductSetEntity.getId(), priceProductSetEntity));
        }
        List<PriceProductSetEntity> addPriceProductSetList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<PriceProductSetEntity> updateProductSetList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        long now = DateTimeUtil.getInt();
        List<ItemPoJo> businessUnitItems = relativeProductHelp.getBusinessUnitItems(corpid);
        for (int i = 0; i < dataList.size(); i++) {
            JSONObject priceProductData = dataList.getJSONObject(i);
            Long businessProductId = priceProductData.getLongValue(StringConstant.BUSINESS_PRODUCT_ID);
            boolean addProductFlag = formDataValidateProductHelp.addProductFlag(businessProductId);
            // 产品数据
            if (!Objects.equals(priceProductSetSaveDTO.getIsImport(), BasicConstant.ONE)) {
                JSONObject product = priceProductData.getJSONObject(ProductEnum.NAME.getAttr());
                JSONObject productData = product.getJSONObject(StringConstant.JSON_DATA);
                priceProductData.put(PriceProductEnum.PARENT_ID.getAttr(), productData.getLongValue(ProductEnum.PARENT_ID.getAttr()));
                priceProductData.put(BusinessConstant.ID, product.getLongValue(StringConstant.DATA_ID));
                if (productData.getJSONObject(ProductConstant.TRANSFORM_UNIT_RATE) != null) {
                    MultiUnitItemPoJo multiUnitItemPoJo = productData.getJSONObject(ProductConstant.TRANSFORM_UNIT_RATE).toJavaObject(MultiUnitItemPoJo.class);
                    priceProductData.put(ProductConstant.TRANSFORM_UNIT_RATE, multiUnitItemPoJo.getItemDataPoJoList());
                }
                priceProductData.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                priceProductData.put(PriceProductEnum.NAME.getSaasAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                priceProductData.put(PriceProductEnum.SPECIFICATION.getSaasAttr(), productData.getString(ProductEnum.SPECIFICATION.getAttr()));
            }

            String unitStr = "";
            if (priceProductData.containsKey(PriceProductEnum.UNIT.getAttr())) {
                if (priceProductData.get(PriceProductEnum.UNIT.getAttr()) instanceof JSONObject) {
                    // 多单位
                    JSONObject unitObj = priceProductData.getJSONObject(PriceProductEnum.UNIT.getAttr());
                    unitStr = unitObj.getString(StringConstant.TEXT);
                } else if (priceProductData.get(PriceProductEnum.UNIT.getAttr()) instanceof String) {
                    // 单单位
                    unitStr = priceProductData.getString(PriceProductEnum.UNIT.getAttr());
                }
                int enableMultiUnit = priceProductData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                if (BasicConstant.ONE.equals(enableMultiUnit)) {
                    List<UnitItemPoJo> unitItemPoJos = priceProductData.getJSONArray(ProductConstant.TRANSFORM_UNIT_RATE).toJavaList(UnitItemPoJo.class);
                    for (UnitItemPoJo unitItemPoJo : unitItemPoJos) {
                        if (Objects.equals(unitItemPoJo.getText(), unitStr)) {
                            priceProductData.put("isBase", unitItemPoJo.getIsBase());
                            priceProductData.put(PriceProductEnum.UNIT.getAttr(), unitItemPoJo.getValue());
                            break;
                        }
                    }
                } else {
                    priceProductData.put("isBase", 1);
                    for (ItemPoJo businessUnitItem : businessUnitItems) {
                        if (Objects.equals(unitStr, businessUnitItem.getText())) {
                            priceProductData.put(PriceProductEnum.UNIT.getAttr(), businessUnitItem.getValue());
                        }
                    }
                }

            } else {
                priceProductData.put("isBase", 1);
            }
            // 价目产品售价上下限校验
            Double sellingPrice = priceProductData.getDouble(PriceProductEnum.SELLING_PRICE.getAttr());
            Double sellingPriceUp = priceProductData.getDouble(PriceProductEnum.SELLING_PRICE_UP.getAttr());
            Double sellingPriceDown = priceProductData.getDouble(PriceProductEnum.SELLING_PRICE_DOWN.getAttr());
            // 售价上限/下限，只要有一个填写了，另一个就必填
            if (sellingPriceUp != null && sellingPriceDown == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.HAS_PRICE_UP_NO_DOWN), priceProductData.getString(PriceProductEnum.NAME.getSaasAttr()), priceProductData.getString(PriceProductEnum.SPECIFICATION.getSaasAttr())));
            } else if (sellingPriceUp == null && sellingPriceDown != null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.HAS_PRICE_DOWN_NO_UP), priceProductData.getString(PriceProductEnum.NAME.getSaasAttr()), priceProductData.getString(PriceProductEnum.SPECIFICATION.getSaasAttr())));
            }
            if (Objects.nonNull(sellingPriceUp) && Arith.comperaTwoDoubleByAccuracy(sellingPriceUp, 0.0D, 2) && Arith.compare(sellingPriceUp, sellingPrice) < 0) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.SELLING_PRICE_RANGE), priceProductData.getString(PriceProductEnum.NAME.getSaasAttr()), sellingPriceUp, sellingPriceDown));
            }
            if (Objects.nonNull(sellingPriceDown) && Arith.comperaTwoDoubleByAccuracy(sellingPriceDown, 0.0D, 2) && Arith.compare(sellingPriceDown, sellingPrice) > 0) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.SELLING_PRICE_RANGE), priceProductData.getString(PriceProductEnum.NAME.getSaasAttr()), sellingPriceUp, sellingPriceDown));
            }
            PriceProductSetEntity priceProductSetEntity;
            if (addProductFlag) {
                priceProductSetEntity = new PriceProductSetEntity();
                priceProductSetEntity.setCorpid(corpid);
                priceProductSetEntity.setPriceId(dataId);
                priceProductSetEntity.setProductId(priceProductData.getLongValue(BusinessConstant.ID));
                priceProductSetEntity.setParentId(priceProductData.getLongValue(PriceProductEnum.PARENT_ID.getAttr()));
                priceProductSetEntity.setProductUnit(priceProductData.getString(PriceProductEnum.UNIT.getAttr()));
                priceProductSetEntity.setIsBase(priceProductData.getIntValue("isBase"));
                priceProductSetEntity.setProductPrice(priceProductData.getDoubleValue(ProductEnum.PRICE.getAttr()));
                priceProductSetEntity.setAddTime(now);
                priceProductSetEntity.setDel(BasicConstant.ZERO);
                addPriceProductSetList.add(priceProductSetEntity);
            } else if (orginProductMap.containsKey(businessProductId)) {
                priceProductSetEntity = orginProductMap.get(businessProductId);
                updateProductSetList.add(priceProductSetEntity);
                //只剩删除的产品
                orginProductMap.remove(businessProductId);
            } else {
                //删除产品
                continue;
            }

            priceProductSetEntity.setDiscount(priceProductData.getDoubleValue(PriceProductEnum.DISCOUNT.getAttr()));
            priceProductSetEntity.setSellingPrice(sellingPrice);
            priceProductSetEntity.setPriceCap(sellingPriceUp);
            priceProductSetEntity.setPriceFloor(sellingPriceDown);
            priceProductSetEntity.setUpdateTime(now);

        }
        if (CollectionsUtil.isNotEmpty(addPriceProductSetList)) {
            priceProductSetModel.insertBatch(addPriceProductSetList);
        }
        if (CollectionsUtil.isNotEmpty(updateProductSetList)) {
            priceProductSetModel.updateBatch(updateProductSetList, corpid);
        }
        for (Map.Entry<Long, PriceProductSetEntity> entry : orginProductMap.entrySet()) {
            PriceProductSetEntity delProduct = entry.getValue();
            priceProductSetModel.deleteByProductId(delProduct.getId(),delProduct.getProductId(), delProduct.getCorpid());
        }

        return priceProductSetSaveVO;
    }

    @Override
    public PriceSetGetVO editPriceSet(PriceSetGetDTO priceSetGetDTO) throws XbbException {
        PriceSetGetVO priceSetGetVO = new PriceSetGetVO();
        String corpid = priceSetGetDTO.getCorpid();
        Long dataId = priceSetGetDTO.getDataId();

        PriceSetEntity priceSetEntity = priceSetModel.getByKey(dataId, corpid);
        if (priceSetEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);
        }
        if (priceSetEntity.getRule() != null) {
            // 处理有员工或部门的筛选条件
            conditionHelper.handleUserConditions(corpid, priceSetEntity.getRule());
        }

        priceSetGetVO.setData(priceSetEntity);
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
        return priceSetGetVO;
    }

    @Override
    public PaasFormDataEsListVO getProductSearchList(ProductListDataDTO productListDataDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        String corpid = productListDataDTO.getCorpid();
        List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions() == null ? new ArrayList<>() : productListDataDTO.getConditions();
        //解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (paasFormExplainEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        // 分类筛选
        if (productListDataDTO.getCategoryId() != null) {
            List<Long> categoryIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, productListDataDTO.getCategoryId());
            productCategoryList.forEach((item) -> {
                categoryIdIn.add(item.getId());
            });
            if (!categoryIdIn.isEmpty()) {
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.CATEGORY_ID.getAttr(), "", ProductEnum.CATEGORY_ID.getFieldType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(categoryIdIn)));
            }
        }
        Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator();
        while (iterator.hasNext()) {
            ConditionsEntityExt entityExt = iterator.next();
            if (entityExt.getAttr().equals(ProductEnum.SPECIFICATION.getAttr())) {
                entityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                break;
            }
        }
        List<String> fieldList = BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        explainList = handleExplain(explainList, fieldList);
        explainList.removeIf(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttrName(), "标签"));
        //查询
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("data." + ProductEnum.ENABLE_SKU.getAttr(), 1));
        boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), 0));
        boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.ONLINE.getAttr(), 0));
        EsUtil.parseCondition(boolQueryBuilder, conditionsEntityExtList, "", corpid, XbbRefTypeEnum.PRODUCT.getCode());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.sort(new FieldSortBuilder("updateTime").order(SortOrder.DESC));
        sourceBuilder.query(boolQueryBuilder);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, productListDataDTO.getPage(), productListDataDTO.getPageSize());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        if (esEntities == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        PageHelper pageHelper = new PageHelper(productListDataDTO.getPage(), productListDataDTO.getPageSize());
        pageHelper.setRowsCount((int) esEntities.getTotalElements());
        formDataListVO.setPageHelper(pageHelper);
        formDataListVO.setPaasFormDataESList(esEntities.getContent());
        productService.setChildSpecification(formDataListVO.getPaasFormDataESList(), productListDataDTO.getCorpid());
        formDataListVO.setHeadList(explainList);
        formDataListVO.setForm(paasFormEntityExt);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        List<ItemPoJo> productItems = saasFormHelp.getProductItems(corpid);
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
            if (Objects.equals(ProductEnum.UNIT.getAttr(), item.getAttr())) {
                if (CollectionsUtil.isNotEmpty(productItems)) {
                    item.setItems(productItems);
                }
            }
        });
        // 多单位产品
        Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
        Set<Long> productIdSet = new HashSet<>();
        formDataListVO.getPaasFormDataESList().forEach(paasFormDataEntityExt -> productIdSet.add(paasFormDataEntityExt.getId()));
        Map<Long, List<MultiUnitPricePoJo>> priceMapByProductIdSet = productUnitPriceModel.getPriceMapByProductIdSet(corpid, productIdSet);
        for (PaasFormDataEntityExt paasFormDataEntityExt : formDataListVO.getPaasFormDataESList()) {
            JSONObject productData = paasFormDataEntityExt.getData();
            if (Objects.nonNull(productData) && CollectionsUtil.isEmpty(productData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                productData.put(ProductEnum.PRODUCT_IMGS.getAttr(), productData.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
            }
            paasFormDataEntityExt.setSourceData(productData);
            if (BasicConstant.ZERO.equals(productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()))) {
                continue;
            }
            if (productData.getLongValue(ProductEnum.UNIT.getAttr()) <= 0) {
                continue;
            }
            // 单价
            List<MultiUnitPricePoJo> multiUnitPricePoJos = priceMapByProductIdSet.get(paasFormDataEntityExt.getId());
            productData.put(ProductConstant.PRICE, multiUnitPricePoJos);
            long groupId = productData.getLongValue(ProductEnum.UNIT.getAttr());
            MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(groupId);
            productData.put(ProductConstant.TRANSFORM_UNIT_RATE, multiUnitItemPoJo);
        }
        saasListHelp.analysisSaasDataList(formDataListVO, explainMap);
        return formDataListVO;
    }

    @Override
    public BaseVO sort(PriceSetSortDTO priceSetSortDTO) throws XbbException {
        List<PriceSetEntity> list = priceSetSortDTO.getList();
        String corpid = priceSetSortDTO.getCorpid();
        if (CollectionsUtil.isNotEmpty(list)) {
            priceSetModel.updateBatch(list, corpid);
        }
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
        return new BaseVO();
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        String corpid = importFormDataDTO.getCorpid();
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);

        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();

            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);

            if (Objects.equals(attr, PriceSetEnum.PRODUCT.getAttr())) {
                importHelper.formatCommonProduct(titlePojoList, dataJson, rowValueList, fieldAttr, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode(), corpid);
            } if (Objects.equals(attr, PriceSetEnum.SCOPE.getAttr())) {
                String scope = cellValue.toString();
                StringBuilder stringBuilder = new StringBuilder("[");
                stringBuilder.append(PriceSetScopeEnum.CONTRACT.getType());
                if (scope.contains(PriceSetScopeEnum.QUOTATION.getName())){
                    stringBuilder.append(",").append(PriceSetScopeEnum.QUOTATION.getType());
                }
                if (scope.contains(PriceSetScopeEnum.SALES_OPPORTUNITY.getName())){
                    stringBuilder.append(",").append(PriceSetScopeEnum.SALES_OPPORTUNITY.getType());
                }
                stringBuilder.append("]");
                dataJson.put(attr, stringBuilder.toString());
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldAttr.getFieldType())) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())) {
                    importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                } else {
                    dataJson.put(attr, cellValue);
                }
            }
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public PaasFormDataEsListVO priceSetList(FormDataListDTO formDataListDTO) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        List<Long> idIn = formDataListDTO.getIdIn();

        List<FieldAttrEntity> headList = getHeadList(corpid);
        // 筛选项
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        conditions = conditions != null ? conditions : new ArrayList<>();
        ConditionsEntityExt productCondition = null;
        CustomerEntityExt customerEntityExt = null;
        List<ConditionEntity> priceConditions = new ArrayList<>();
        for (ConditionsEntityExt condition : conditions) {
            ConditionEntity conditionEntity = new ConditionEntity();
            conditionEntity.setAttr(condition.getAttr());
            conditionEntity.setSymbol(condition.getSymbol());
            if (Objects.equals(condition.getAttr(), PriceSetEnum.PRODUCT.getAttr())) {
                productCondition = condition;
            } else if (Objects.equals(condition.getAttr(), PriceSetEnum.NAME.getAttr())) {
                if (ConditionEnum.IN.getSymbol().equals(condition.getSymbol()) || ConditionEnum.NOIN.getSymbol().equals(condition.getSymbol())) {
                    conditionEntity.setValues(condition.getValue());
                } else {
                    conditionEntity.setValue(CollectionsUtil.isNotEmpty(condition.getValue()) ? condition.getValue().get(0) : "");
                }
                priceConditions.add(conditionEntity);
            } else if (Objects.equals(condition.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr())) {
                if (CollectionsUtil.isNotEmpty(condition.getValue())) {
                    if (ConditionEnum.IN.getSymbol().equals(condition.getSymbol()) || ConditionEnum.NOIN.getSymbol().equals(condition.getSymbol())) {
                        List<Long> customerIds = new ArrayList<>();
                        condition.getValue().forEach(o -> customerIds.add(Long.parseLong(o.toString())));
                        List<CustomerEntityExt> customerList = customerModel.getByKeys(customerIds, corpid);
                        List<Object> formIds = new ArrayList<>();
                        customerList.forEach(customer -> formIds.add(customer.getFormId()));
                        conditionEntity.setValues(formIds);
                    } else {
                        customerEntityExt = customerModel.getByKey(Long.parseLong(condition.getValue().get(0).toString()), corpid);
                        if (Objects.isNull(customerEntityExt)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nMessageUtil.getMessage(MessageConstant.FORM_DATA_NOT_EXIST));
                        }
                        conditionEntity.setValue(customerEntityExt.getFormId());
                    }
                    priceConditions.add(conditionEntity);
                }
            }
        }
        // 价目表
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        if (CollectionsUtil.isNotEmpty(idIn)) {
            param.put(ParameterConstant.ID_IN, idIn);
        }
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.ORDER_BY_STR, "priority ASC");
        List<PriceSetEntity> priceSetList = priceSetModel.getPricesByConditions(param, priceConditions);
        Map<Long, PriceSetEntity> priceMap = new HashMap<>();
        List<Long> priceIds = new ArrayList<>();
        if (customerEntityExt != null) {
            JSONObject data = customerEntityExt.getData();
            List<String> addressAttrList = Arrays.asList("province", "city", "district", "address");
            Outer:
            for (PriceSetEntity priceSetEntity : priceSetList) {
                if (Objects.equals(priceSetEntity.getAdapterType(), BasicConstant.ZERO)) {
                    priceIds.add(priceSetEntity.getId());
                    priceMap.put(priceSetEntity.getId(), priceSetEntity);
                    continue;
                }
                List<ConditionsEntityExt> conditionsEntityExts = priceSetEntity.getRule().toJavaList(ConditionsEntityExt.class);
                for (ConditionsEntityExt conditionsEntityExt : conditionsEntityExts) {
                    String attr = conditionsEntityExt.getAttr();
                    List<Object> value = conditionsEntityExt.getValue();
                    //过滤地址不符合的价目表
                    if (addressAttrList.contains(conditionsEntityExt.getAttr())) {
                        if (Objects.isNull(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr())) || Objects.isNull(value) || value.isEmpty()
                                || !Objects.equals(data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()).getString(conditionsEntityExt.getAttr()), value.get(0).toString())) {
                            continue Outer;
                        }
                    } else if (Objects.equals(conditionsEntityExt.getFieldType(), FieldTypeEnum.SERIALNO.getType())) {
                        data.put(FieldTypeEnum.SERIALNO.getAlias(), customerEntityExt.getSerialNo());
                        if (!webCommonDataValueMatchHandle.match(conditionsEntityExt, data)) {
                            continue Outer;
                        }
                    } else {
                        Object dataValue = data.get(attr);
                        if (dataValue instanceof List) {
                            if (!webListDataValueMatchHandle.match(conditionsEntityExt, data)) {
                                continue Outer;
                            }
                        } else {
                            if (!webCommonDataValueMatchHandle.match(conditionsEntityExt, data)) {
                                continue Outer;
                            }
                        }
                    }
                }
                priceIds.add(priceSetEntity.getId());
                priceMap.put(priceSetEntity.getId(), priceSetEntity);
            }
        } else {
            priceSetList.forEach(priceSetEntity -> {
                        priceMap.put(priceSetEntity.getId(), priceSetEntity);
                        priceIds.add(priceSetEntity.getId());
                    }
            );
        }
        // 价目产品
        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL);
        param.put("priceIdIn", priceIds);
        param.put(ParameterConstant.PRODUCT_ID_IN, productCondition != null ? productCondition.getValue() : null);
        List<PriceProductSetEntity> priceProductSetList = priceProductSetModel.findEntitys(param);
        for (PriceProductSetEntity productSetEntity : priceProductSetList) {
            PriceSetEntity priceSetEntity = priceMap.get(productSetEntity.getPriceId());
            if (priceSetEntity == null) {
                continue;
            }
            List<PriceProductSetEntity> priceProductSets = priceSetEntity.getPriceProductSetList();
            if (CollectionsUtil.isEmpty(priceProductSets)) {
                priceProductSets = new ArrayList<>();
                priceSetEntity.setPriceProductSetList(priceProductSets);
            }
            priceProductSets.add(productSetEntity);
        }

        Set<Long> productIdSet = new HashSet<>();
        for (PriceSetEntity priceSetEntity : priceSetList) {
            List<PriceProductSetEntity> priceProductSets = priceSetEntity.getPriceProductSetList();
            if (CollectionsUtil.isEmpty(priceProductSets)) {
                continue;
            }
            for (PriceProductSetEntity entity : priceProductSets) {
                productIdSet.add(entity.getProductId());
            }
        }
        List<PaasFormDataEntityExt> productEntityList = productService.getProductListById(productIdSet, corpid, DelEnum.NORMAL);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(productEntityList.size());
        productEntityList.forEach(item -> productMap.put(item.getDataId(), item));

        List<PaasFormDataEntityExt> paasFormDataESList = new ArrayList<>(priceSetList.size());
        for (PriceSetEntity priceSetEntity : priceSetList) {
            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setDataId(priceSetEntity.getId());
            JSONObject priceData = new JSONObject();
            priceData.put(PriceSetEnum.NAME.getAttr(), priceSetEntity.getName());
            priceData.put(PriceSetEnum.PRIORITY.getAttr(), priceSetEntity.getPriority());
            priceData.put(PriceSetEnum.START_TIME.getAttr(), priceSetEntity.getStartTime());
            priceData.put(PriceSetEnum.END_TIME.getAttr(), priceSetEntity.getEndTime());
            priceData.put(PriceSetEnum.MEMO.getAttr(), priceSetEntity.getMemo());
            priceData.put(PriceSetEnum.SCOPE.getAttr(), priceSetEntity.getScope());
            priceData.put(PriceSetEnum.ADAPTER_TYPE.getAttr(), priceSetEntity.getFormId());
            if (CollectionsUtil.isNotEmpty(priceSetEntity.getPriceProductSetList())) {
                JSONArray priceProductArray = new JSONArray();
                for (PriceProductSetEntity priceProductSetEntity : priceSetEntity.getPriceProductSetList()) {
                    PaasFormDataEntityExt formDataEntityExt = productMap.get(priceProductSetEntity.getProductId());
                    if (Objects.isNull(formDataEntityExt)) {
                        continue;
                    }
                    JSONObject productData = formDataEntityExt.getData();

                    JSONObject priceProductData = new JSONObject();
                    priceProductData.put(PriceProductEnum.NAME.getAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                    priceProductData.put(PriceProductEnum.PRODUCT_NO.getAttr(), formDataEntityExt.getSerialNo());
                    priceProductData.put(PriceProductEnum.SPECIFICATION.getAttr(), productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                    priceProductData.put(PriceProductEnum.UNIT.getAttr(), priceProductSetEntity.getProductUnit());
                    priceProductData.put(PriceProductEnum.SELLING_PRICE.getAttr(), priceProductSetEntity.getSellingPrice());
                    priceProductData.put(PriceProductEnum.SELLING_PRICE_UP.getAttr(), priceProductSetEntity.getPriceCap());
                    priceProductData.put(PriceProductEnum.SELLING_PRICE_DOWN.getAttr(), priceProductSetEntity.getPriceFloor());
                    priceProductData.put(PriceProductEnum.PRICE.getAttr(), priceProductSetEntity.getProductPrice());
                    priceProductData.put(PriceProductEnum.DISCOUNT.getAttr(), priceProductSetEntity.getDiscount());
                    priceProductArray.add(priceProductData);
                }
                priceData.put(PriceSetEnum.PRODUCT.getAttr(), priceProductArray);
            } else {
                // 产品价目查询列表导出，没有产品的价目表不导出
                if (Objects.equals(formDataListDTO.getSubBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                    continue;
                }
            }

            paasFormDataEntityExt.setData(priceData);
            paasFormDataESList.add(paasFormDataEntityExt);
        }

        PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
        paasFormDataEsListVO.setHeadList(headList);
        paasFormDataEsListVO.setPaasFormDataESList(paasFormDataESList);
        PageHelper pageHelper = new PageHelper();
        pageHelper.setRowsCount(paasFormDataESList.size());
        paasFormDataEsListVO.setPageHelper(pageHelper);
        return paasFormDataEsListVO;
    }

    @Override
    @Transactional(rollbackFor = XbbException.class)
    public FormDataAddVO add(FormDataAddDTO formDataSaveDTO) throws XbbException {
        JSONObject dataList = formDataSaveDTO.getDataList();
        String corpid = formDataSaveDTO.getCorpid();

        PriceSetEntity priceSetEntity = new PriceSetEntity();
        priceSetEntity.setCorpid(corpid);
        priceSetEntity.setName(dataList.getString(PriceSetEnum.NAME.getAttr()));
        priceSetEntity.setPriority(dataList.getInteger(PriceSetEnum.PRIORITY.getAttr()));
        priceSetEntity.setStartTime(dataList.getLong(PriceSetEnum.START_TIME.getAttr()));
        priceSetEntity.setEndTime(dataList.getLong(PriceSetEnum.END_TIME.getAttr()));
        priceSetEntity.setMemo(dataList.getString(PriceSetEnum.MEMO.getAttr()));
        priceSetEntity.setFormId(dataList.getInteger(PriceSetEnum.ADAPTER_TYPE.getAttr()));
        priceSetEntity.setAdapterType(BasicConstant.ZERO);
        priceSetEntity.setScope(dataList.getString(PriceSetEnum.SCOPE.getAttr()));
        priceSetEntity.setRule(new JSONArray());
        priceSetEntity.setEnable(BasicConstant.ZERO);
        // 价目表
        PriceSetSaveDTO priceSetSaveDTO = new PriceSetSaveDTO();
        BeanUtil.copyProperties(formDataSaveDTO, priceSetSaveDTO);
        priceSetSaveDTO.setPriceSet(priceSetEntity);
        priceSetSaveDTO.setIsImport(1);
        savePriceSet(priceSetSaveDTO);
        //价目产品
        JSONArray productArray = dataList.getJSONArray(PriceSetEnum.PRODUCT.getAttr());
        Set<Long> productIds = new HashSet<>();
        Map<Long, JSONObject> productMap = new HashMap<>();
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject jsonObject = productArray.getJSONObject(i);
            productIds.add(jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLongValue(StringConstant.DATA_ID));
        }
        List<PaasFormDataEntityExt> productList = productService.getProductListById(productIds, corpid, DelEnum.NORMAL);
        productService.setChildSpecification(productList, corpid);
        productList.forEach(paasFormDataEntityExt -> productMap.put(paasFormDataEntityExt.getDataId(), paasFormDataEntityExt.getData()));

        if (!productArray.isEmpty()) {
            for (int i = 0; i < productArray.size(); i++) {
                JSONObject productObj = productArray.getJSONObject(i);
                Long productId = productObj.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(BasicConstant.DATAID);
                productObj.put(BasicConstant.ID, productId);
                productObj.put(PriceProductEnum.PARENT_ID.getAttr(), productObj.getLongValue(ProductEnum.PARENT_ID.getSaasAttr()));
                JSONObject productData = productMap.get(productId);
                if (Objects.nonNull(productData)) {
                    productObj.put(PriceProductEnum.NAME.getSaasAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                    productObj.put(PriceProductEnum.SPECIFICATION.getSaasAttr(), productData.getString(ProductEnum.SPECIFICATION.getAttr()));
                }

                int enableMultiUnit = productObj.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                Object unitObj = productObj.get(SelectProductEnum.UNIT.getAttr());
                JSONObject unit = new JSONObject();
                if (BasicConstant.ONE.equals(enableMultiUnit)) {
                    List<ItemPoJo> itemPoJos = productObj.getJSONArray(ProductConstant.TRANSFORM_UNIT_RATE).toJavaList(ItemPoJo.class);
                    for (ItemPoJo itemPoJo : itemPoJos) {
                        if (Objects.equals(itemPoJo.getText(), unitObj.toString())) {
                            unit.put(StringConstant.TEXT, itemPoJo.getText());
                            unit.put(StringConstant.VALUE, itemPoJo.getValue());
                            productObj.put(PriceProductEnum.UNIT.getAttr(), unit);
                            break;
                        }
                    }
                } else {
                    String unitVal = productData.getString(ProductEnum.UNIT.getAttr());
                    //不管导入填了什么，直接不管，采用产品原有单位值
//                    if (Objects.nonNull(unitObj)) {
//                        unit.put(StringConstant.VALUE, unitVal);
//                        if (unitObj instanceof JSONObject) {
//                            unit.put(StringConstant.TEXT, ((JSONObject) unitObj).getString("text"));
//                        } else {
//                            unit.put(StringConstant.TEXT, unitObj.toString());
//                        }
//                        productObj.put(PriceProductEnum.UNIT.getAttr(), unit);
//                    }
                    productObj.put(PriceProductEnum.UNIT.getAttr(), unitVal);
                }
            }
            PriceProductSetSaveDTO priceProductSetSaveDTO = new PriceProductSetSaveDTO();
            BeanUtil.copyProperties(formDataSaveDTO, priceProductSetSaveDTO);
            priceProductSetSaveDTO.setSupplierProducts(productArray);
            priceProductSetSaveDTO.setDataId(priceSetEntity.getId());
            priceProductSetSaveDTO.setIsImport(BasicConstant.ONE);
            savePriceProductSet(priceProductSetSaveDTO);
        }
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
        return new FormDataAddVO();
    }

    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        // 多单位
        List<ItemPoJo> businessUnitItems = relativeProductHelp.getBusinessUnitItems(corpid);

        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            JSONObject data = paasFormDataEntityExt.getData();

            data.put(PriceSetEnum.START_TIME.getAttr(), DateTimeUtil.getDateStringEpochSecond(data.getLongValue(PriceSetEnum.START_TIME.getAttr())));
            data.put(PriceSetEnum.END_TIME.getAttr(), DateTimeUtil.getDateStringEpochSecond(data.getLongValue(PriceSetEnum.END_TIME.getAttr())));

            //价目产品
            JSONArray jsonArray = data.getJSONArray(PriceSetEnum.PRODUCT.getAttr());
            if (CollectionsUtil.isNotEmpty(jsonArray)) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String unitStr = jsonObject.getString(PriceProductEnum.UNIT.getAttr());
                    for (ItemPoJo itemPoJo : businessUnitItems) {
                        if (StringUtil.isNotEmpty(unitStr, true) && Objects.equals(itemPoJo.getValue().toString(), unitStr)) {
                            jsonObject.put(PriceProductEnum.UNIT.getAttr(), itemPoJo.getText());
                            break;
                        }
                    }
                }
            }
            //处理适用表单
            String scope = data.getString(PriceSetEnum.SCOPE.getAttr());
            StringBuilder stringBuilder = new StringBuilder(PriceSetScopeEnum.CONTRACT.getName());
            if (scope.contains(PriceSetScopeEnum.QUOTATION.getType().toString())){
                stringBuilder.append(",").append(PriceSetScopeEnum.QUOTATION.getName());
            }
            if (scope.contains(PriceSetScopeEnum.SALES_OPPORTUNITY.getType().toString())){
                stringBuilder.append(",").append(PriceSetScopeEnum.SALES_OPPORTUNITY.getName());
            }
            data.put(PriceSetEnum.SCOPE.getAttr(), stringBuilder.toString());
        }
    }

    @Override
    public PriceProductSetVO getLinkProductField(PriceProductSetDTO priceProductSetDTO) throws XbbException {
        PriceProductSetVO priceProductSetVO = new PriceProductSetVO();
        List<FieldAttrEntity> headList = getHeadList(priceProductSetDTO.getCorpid());
        List<? extends FieldAttrEntity> items = headList.get(0).getSubForm().getItems();
        List<String> removeAttr = Arrays.asList(PriceProductEnum.SPECIFICATION.getAttr(), PriceProductEnum.PRODUCT_NO.getAttr(), PriceProductEnum.PRODUCT_IMGS.getAttr());
        items.removeIf(fieldAttrEntity -> removeAttr.contains(fieldAttrEntity.getAttr()));
        items.forEach(fieldAttrEntity -> {
            fieldAttrEntity.setTheWidth(160L);
            if (Objects.equals(fieldAttrEntity.getAttr(), PriceProductEnum.NAME.getAttr())) {
                fieldAttrEntity.setEditable(BasicConstant.ZERO);
                fieldAttrEntity.getLinkInfo().getLinkedAttr().removeIf(linkedAttrPoJo -> Objects.equals(linkedAttrPoJo.getAttrName(), "标签"));
            }
        });

        headList.get(0).setFieldType(FieldTypeEnum.SELECT_PRODUCT.getType());
        Long dataId = priceProductSetDTO.getDataId();

        List<Long> productIdList = priceProductSetModel.getAllProduct(priceProductSetDTO.getCorpid(), dataId);
        JSONObject permission = new JSONObject();
        permission.put("editable", true);
        permission.put("productAdd", true);
        permission.put("productPriceEdit", true);

        priceProductSetVO.setExplainList(headList);
        priceProductSetVO.setProductIdIn(productIdList != null ? productIdList : new ArrayList<>());
        priceProductSetVO.setPermission(permission);
        return priceProductSetVO;
    }

    @Override
    public BaseVO deleteProductPrice(PriceProductSetDelDTO priceProductSetDelDTO) throws XbbException {
        String corpid = priceProductSetDelDTO.getCorpid();
        Long dataId = priceProductSetDelDTO.getDataId();
        Long productId = priceProductSetDelDTO.getProductSubId();

        priceProductSetModel.deleteByProductId(dataId, productId, corpid);

        return new BaseVO();
    }

    /**
     * 导入查重
     *
     * @param formDataRepeatDTO 入参
     * @param repeatValueMap    价目名称
     * @return FormDataRepeatVO
     * @throws XbbException 异常
     */
    @Override
    public FormDataRepeatVO importRepeat(FormDataRepeatDTO formDataRepeatDTO, Map<String, Object> repeatValueMap) throws XbbException {
        FormDataRepeatVO formDataRepeatVO = new FormDataRepeatVO();
        String corpid = formDataRepeatDTO.getCorpid();
        Object name = repeatValueMap.get(PriceSetEnum.NAME.getAttr());

        List<PaasFormDataEntityExt> formDataList = new ArrayList<>();
        PriceSetEntity priceSetEntity = priceSetModel.getByName(name.toString(), corpid);
        if (Objects.nonNull(priceSetEntity)) {
            JSONObject data = new JSONObject();
            data.put(PriceSetEnum.NAME.getAttr(), priceSetEntity.getName());
            data.put(PriceSetEnum.START_TIME.getAttr(), priceSetEntity.getStartTime());
            data.put(PriceSetEnum.END_TIME.getAttr(), priceSetEntity.getEndTime());
            data.put(PriceSetEnum.MEMO.getAttr(), priceSetEntity.getMemo());
            data.put(PriceSetEnum.ADAPTER_TYPE.getAttr(), priceSetEntity.getAdapterType());

            PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
            paasFormDataEntityExt.setId(priceSetEntity.getId());
            paasFormDataEntityExt.setFormId(formDataRepeatDTO.getFormId());
            paasFormDataEntityExt.setDataId(priceSetEntity.getId());
            paasFormDataEntityExt.setData(data);
            formDataList.add(paasFormDataEntityExt);
        }


        formDataRepeatVO.setFormDataList(formDataList);
        return formDataRepeatVO;
    }

    @Transactional(rollbackFor = XbbException.class)
    @Override
    public void importCover(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        String corpid = formDataUpdateDTO.getCorpid();
        Long dataId = formDataUpdateDTO.getDataId();
        JSONObject dataList = formDataUpdateDTO.getDataList();


        PriceSetEntity priceSetEntity = new PriceSetEntity();
        priceSetEntity.setId(dataId);
        priceSetEntity.setCorpid(corpid);
        priceSetEntity.setName(dataList.getString(PriceSetEnum.NAME.getAttr()));
        priceSetEntity.setStartTime(dataList.getLong(PriceSetEnum.START_TIME.getAttr()));
        priceSetEntity.setEndTime(dataList.getLong(PriceSetEnum.END_TIME.getAttr()));
        priceSetEntity.setMemo(dataList.getString(PriceSetEnum.MEMO.getAttr()));
        priceSetEntity.setFormId(dataList.getInteger(PriceSetEnum.ADAPTER_TYPE.getAttr()));
        // 价目表
        PriceSetSaveDTO priceSetSaveDTO = new PriceSetSaveDTO();
        BeanUtil.copyProperties(formDataUpdateDTO, priceSetSaveDTO);
        priceSetSaveDTO.setPriceSet(priceSetEntity);
        priceSetSaveDTO.setIsImport(1);
        savePriceSet(priceSetSaveDTO);
        // 价目产品
        List<PriceProductSetEntity> priceProductSets = priceProductSetModel.getByPriceId(dataId, corpid);
        if (CollectionsUtil.isEmpty(priceProductSets)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        Map<String, Long> originMap = new HashMap<>();
        priceProductSets.forEach(priceProductSetEntity -> {
            if (Objects.nonNull(priceProductSetEntity.getProductUnit())) {
                originMap.put(priceProductSetEntity.getProductId() + "_" + priceProductSetEntity.getProductUnit(), priceProductSetEntity.getId());
            } else {
                originMap.put(priceProductSetEntity.getProductId().toString(), priceProductSetEntity.getId());
            }
        });

        JSONArray jsonArray = dataList.getJSONArray(PriceSetEnum.PRODUCT.getAttr());
        Set<Long> productIds = new HashSet<>();
        Map<Long, JSONObject> productMap = new HashMap<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            productIds.add(jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLongValue(StringConstant.DATA_ID));
        }
        List<PaasFormDataEntityExt> productList = productService.getProductListById(productIds, corpid, DelEnum.NORMAL);
        productService.setChildSpecification(productList, corpid);
        productList.forEach(paasFormDataEntityExt -> productMap.put(paasFormDataEntityExt.getDataId(), paasFormDataEntityExt.getData()));

        if (!jsonArray.isEmpty()) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Long productId = jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(BasicConstant.DATAID);
                jsonObject.put(BasicConstant.ID, jsonObject.getJSONObject(SelectProductEnum.PRODUCT.getAttr()).getLong(BasicConstant.DATAID));
                jsonObject.put(PriceProductEnum.PARENT_ID.getAttr(), jsonObject.getLongValue(ProductEnum.PARENT_ID.getSaasAttr()));
                JSONObject productData = productMap.get(productId);
                if (Objects.nonNull(productData)) {
                    jsonObject.put(PriceProductEnum.NAME.getSaasAttr(), productData.getString(ProductEnum.NAME.getAttr()));
                    jsonObject.put(PriceProductEnum.SPECIFICATION.getSaasAttr(), productData.getString(ProductEnum.SPECIFICATION.getAttr()));
                }
                int enableMultiUnit = jsonObject.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr());
                Object unitObj = jsonObject.get(SelectProductEnum.UNIT.getAttr());
                ItemPoJo unitItem = new ItemPoJo();
                JSONObject unit = new JSONObject();
                if (BasicConstant.ONE.equals(enableMultiUnit)) {
                    List<ItemPoJo> itemPoJos = jsonObject.getJSONArray(ProductConstant.TRANSFORM_UNIT_RATE).toJavaList(ItemPoJo.class);
                    for (ItemPoJo itemPoJo : itemPoJos) {
                        if (Objects.equals(itemPoJo.getText(), unitObj.toString())) {
                            unitItem = itemPoJo;
                            unit.put(StringConstant.TEXT, itemPoJo.getText());
                            unit.put(StringConstant.VALUE, itemPoJo.getValue());
                            jsonObject.put(PriceProductEnum.UNIT.getAttr(), unit);
                            break;
                        }
                    }
                } else {
                    String unitVal = productData.getString(ProductEnum.UNIT.getAttr());
                    //不管导入填了什么，直接不管，采用产品原有单位值
//                    if (Objects.nonNull(unitObj)) {
//                        unit.put(StringConstant.VALUE, unitVal);
//                        if (unitObj instanceof JSONObject) {
//                            unit.put(StringConstant.TEXT, ((JSONObject) unitObj).getString("text"));
//                            unitItem.setText(((JSONObject) unitObj).getString("text"));
//                        } else {
//                            unit.put(StringConstant.TEXT, unitObj.toString());
//                            unitItem.setText(unitObj.toString());
//                        }
//                        unitItem.setValue(unitVal);
//                        jsonObject.put(PriceProductEnum.UNIT.getAttr(), unit);
//                    }
                    jsonObject.put(PriceProductEnum.UNIT.getAttr(), unitVal);
                }

                String key = "";
                if (Objects.nonNull(unitItem.getValue())) {
                    key = productId + "_" + unitItem.getValue().toString();
                } else {
                    key = productId.toString();
                }
                Long productSubId = originMap.getOrDefault(key, 0L);
                if (productSubId > 0L) {
                    jsonObject.put(StringConstant.BUSINESS_PRODUCT_ID, productSubId);
                }
            }
            PriceProductSetSaveDTO priceProductSetSaveDTO = new PriceProductSetSaveDTO();
            BeanUtil.copyProperties(formDataUpdateDTO, priceProductSetSaveDTO);
            priceProductSetSaveDTO.setSupplierProducts(jsonArray);
            priceProductSetSaveDTO.setDataId(priceSetEntity.getId());
            priceProductSetSaveDTO.setIsImport(BasicConstant.ONE);
            savePriceProductSet(priceProductSetSaveDTO);
        }
        paasRedisHelper.removeValue(RedisPrefixConstant.PRICE_ID_LIST, corpid);
    }

    private List<FieldAttrEntity> handleExplain(List<FieldAttrEntity> explainList, List<String> fieldList) {
        List<Integer> fieldType = Arrays.asList(FieldTypeEnum.DEPT.getType(), FieldTypeEnum.DEPT_GROUP.getType(), FieldTypeEnum.USER.getType(), FieldTypeEnum.USER_GROUP.getType(), FieldTypeEnum.LINK_DATA.getType(), FieldTypeEnum.SEPARATOR.getType(), FieldTypeEnum.ADDRESS.getType(), FieldTypeEnum.LOCATION.getType(), FieldTypeEnum.IMAGE.getType(), FieldTypeEnum.UPLOAD.getType(), FieldTypeEnum.SUB_FORM.getType(), FieldTypeEnum.MEMO.getType());
        return explainList.stream().filter(fieldAttrEntity -> (fieldList.contains(fieldAttrEntity.getAttr()) || (BasicConstant.ONE.equals(fieldAttrEntity.getIsRedundant()) && !fieldType.contains(fieldAttrEntity.getFieldType())))).collect(Collectors.toList());
    }


    /**
     * 获取字段筛选项
     *
     * @param corpid 公司id
     * @param formId 客户表单id
     * @param alias  字段别名
     * @return
     * @throws XbbException
     */
    private List<KeyValuePojo> getValueArr(String corpid, Long formId, String alias) throws XbbException {
        List<KeyValuePojo> jsonArray = new ArrayList<>();
        List<ItemPoJo> valueArr = new ArrayList<>();
        if (CustomerManagementEnum.GENRE.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_GENRE, corpid, formId);
        } else if (CustomerManagementEnum.TYPE.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STATUS, corpid, formId);
        } else if (CustomerManagementEnum.IS_INDIVIDUAL.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_IS_INDIVIDUAL, corpid, formId);
        } else if (CustomerManagementEnum.INDUSTRY.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_INDUSTRY, corpid, formId);
        } else if (CustomerManagementEnum.SOURCE.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_SOURCE, corpid, formId);
        } else if (CustomerManagementEnum.COUNTRY.getAttr().equals(alias)) {
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_COUNTRY, corpid, formId);
        } else if (CustomerManagementEnum.SCALE.getAttr().equals(alias)) {
            // 客户分级
            valueArr = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_SCALE, corpid, formId);
        }

        if (valueArr != null && valueArr.size() > 0) {
            for (ItemPoJo poJo : valueArr) {
                jsonArray.add(new KeyValuePojo(poJo.getText(), poJo.getValue()));
            }
        }
        return jsonArray;
    }

    /**
     * itemPojo转化为KeyValuePojo
     * TODO 后面还要改造
     *
     * @param valueArr itemPojo列表
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-02 12:41
     * @version v1.0
     * @since v1.0
     */
    private List<KeyValuePojo> format2KeyValuePojo(List<ItemPoJo> valueArr) {
        List<KeyValuePojo> resultList = new ArrayList<>();
        if (valueArr != null && valueArr.size() > 0) {
            for (ItemPoJo poJo : valueArr) {
                resultList.add(new KeyValuePojo(poJo.getText(), poJo.getValue()));
            }
        }
        return resultList;
    }

    /**
     * 格式化筛选的数据
     *
     * @param selectInfo  筛选的数据
     * @param name        名称
     * @param alias       别名
     * @param fieldType   类型
     * @param valueArr    值数组
     * @param initValue   初始值
     * @param isRedundant 是否扩展字段
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-06 14:10
     * @version v1.0
     * @since v1.0
     */
    private List<JSONObject> getByType(List<JSONObject> selectInfo, String name, String alias, Integer fieldType,
                                       List<KeyValuePojo> valueArr, String initValue, Integer isRedundant) {

        JSONObject redundantJson = new JSONObject();
        JSONArray redundantSymbol = new JSONArray();
        JSONArray provinceSymbol = new JSONArray();

        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
        if (fieldTypeEnum == null) {
            return selectInfo;
        }

        // 是否放入返回结果
        boolean isPut = false;
        switch (fieldTypeEnum) {
            // 单行、多行
            case TEXT:
            case TEXTAREA:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                isPut = true;
                break;
            // 数字输入
            case NUM:
            case DATETIME:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.GREATERTHAN);
                symbolRelation(redundantSymbol, ConditionEnum.LESSTHAN);
                symbolRelation(redundantSymbol, ConditionEnum.GREATEREQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LESSEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.RANGE);
                isPut = true;
                break;
            // 下拉、复选框组
            case COMBO:
            case CHECKBOX_GROUP:
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 图片多图
            case IMAGE:
                break;
            // 文本上传
            case UPLOAD:
                break;
            // 单选按钮、流水号
            case RADIO_GROUP:
            case SERIALNO:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.NOIN);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 下拉复选框、成员多选、部门多选
            case COMBO_CHECK:
            case USER_GROUP:
            case DEPT_GROUP:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.INCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.ALLINCLUDE);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 成员单选、创建人、所属部门、部门单选
            case USER:
            case CREATORID:
            case DEPARTMENTID:
            case DEPT:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.NOIN);
                symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 添加时间、更新时间
            case ADDTIME:
            case UPDATETIME:
                symbolRelation(redundantSymbol, ConditionEnum.GREATEREQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.LESSEQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.RANGE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            // 负责人
            case OWNERID:
                symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                symbolRelation(redundantSymbol, ConditionEnum.IN);
                symbolRelation(redundantSymbol, ConditionEnum.ALLINCLUDE);
                redundantJson.put("valueArrMap", valueArr);
                isPut = true;
                break;
            default:
                // 地址，省市区
                if (CustomerManagementEnum.ADDRESS.getAttr().equals(alias)) {
                    symbolRelation(provinceSymbol, ConditionEnum.EQUAL);
                    symbolRelation(provinceSymbol, ConditionEnum.NOEQUAL);
                    symbolRelation(provinceSymbol, ConditionEnum.LIKE);
                    symbolRelation(provinceSymbol, ConditionEnum.NOLIKE);
                    symbolRelation(provinceSymbol, ConditionEnum.EMPTY);
                    symbolRelation(provinceSymbol, ConditionEnum.NOEMPTY);
                    symbolRelation(provinceSymbol, ConditionEnum.IN);
                    symbolRelation(provinceSymbol, ConditionEnum.NOIN);
                    redundantJson.put("name", I18nMessageUtil.getMessage(CommonConstant.PROVINCE));
                    redundantJson.put("alias", "province");
                    redundantJson.put("symbolArray", provinceSymbol);
                    redundantJson.put("type", FieldTypeEnum.PUBLIC_GROUP_PROVINCE.getType());
                    redundantJson.put("isRedundant", isRedundant);
                    redundantJson.put("symbol", "");
                    selectInfo.add(redundantJson);
                    symbolRelation(redundantSymbol, ConditionEnum.EQUAL);
                    symbolRelation(redundantSymbol, ConditionEnum.NOEQUAL);
                    symbolRelation(redundantSymbol, ConditionEnum.LIKE);
                    symbolRelation(redundantSymbol, ConditionEnum.NOLIKE);
                    symbolRelation(redundantSymbol, ConditionEnum.EMPTY);
                    symbolRelation(redundantSymbol, ConditionEnum.NOEMPTY);
                    JSONObject redundantJsonCity = new JSONObject();
                    redundantJsonCity.put("name", I18nMessageUtil.getMessage(CommonConstant.CITY));
                    redundantJsonCity.put("alias", "city");
                    redundantJsonCity.put("symbolArray", redundantSymbol);
                    redundantJsonCity.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonCity.put("isRedundant", isRedundant);
                    redundantJsonCity.put("symbol", "");
                    selectInfo.add(redundantJsonCity);
                    JSONObject redundantJsonDistrict = new JSONObject();
                    redundantJsonDistrict.put("name", I18nMessageUtil.getMessage(CommonConstant.AREA));
                    redundantJsonDistrict.put("alias", "district");
                    redundantJsonDistrict.put("symbolArray", redundantSymbol);
                    redundantJsonDistrict.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonDistrict.put("isRedundant", isRedundant);
                    redundantJsonDistrict.put("symbol", "");
                    selectInfo.add(redundantJsonDistrict);
                    JSONObject redundantJsonAddress = new JSONObject();
                    redundantJsonAddress.put("name", CustomerExpressEnum.ADDRESS.getName());
                    redundantJsonAddress.put("alias", "address");
                    redundantJsonAddress.put("symbolArray", redundantSymbol);
                    redundantJsonAddress.put("type", FieldTypeEnum.TEXT.getType());
                    redundantJsonAddress.put("isRedundant", isRedundant);
                    redundantJsonAddress.put("symbol", "");
                    selectInfo.add(redundantJsonAddress);
                }
                break;
        }

        if (isPut) {
            redundantJson.put("name", name);
            redundantJson.put("alias", alias);
            redundantJson.put("isRedundant", isRedundant);
            redundantJson.put("symbolArray", redundantSymbol);
            redundantJson.put("symbol", "");
            redundantJson.put("type", fieldType);
            selectInfo.add(redundantJson);
        }

        return selectInfo;
    }

    /**
     * 获取字段筛选条件
     *
     * @param redundantSymbol 字段条件数据
     * @param symbolEnum      条件枚举
     * @return
     * @throws
     * @author hongxiao
     * @date: 2019-03-06 13:52
     * @version v1.0
     * @since v1.0
     */
    private void symbolRelation(JSONArray redundantSymbol, ConditionEnum symbolEnum) {
        String symbol = symbolEnum.getSymbol();
        String name = symbolEnum.getMemo();
        Map<String, Object> param = new HashMap<>(8);
        param.put("key", symbol);
        param.put("value", name);
        redundantSymbol.add(param);
    }


}
